<template>
  <div>
    <el-popover
      placement="bottom"
      width="500"
      trigger="hover"
      content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。"
      @show="getAdmins"
    >
      <div class="flexBet">
        <div>管理员信息</div>
        <i class="el-icon-edit shou" @click="setOpen = true"></i>
      </div>
      <el-table v-loading="loading" style="margin-top: 10px" :data="gridData">
        <el-table-column
          align="center"
          property="nickName"
          label="姓名"
        ></el-table-column>
        <el-table-column
          align="center"
          property="account"
          label="账号"
        ></el-table-column>
        <el-table-column
          align="center"
          property="phoneNumber"
          label="手机号码"
        ></el-table-column>
      </el-table>
      <pagination
        v-show="params.total > 0"
        :total="params.total"
        :page.sync="params.pageNum"
        :limit.sync="params.pageSize"
        @pagination="getAdmins"
      />
      <!-- 管理员列表 -->
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        title="管理员设置"
        :visible.sync="setOpen"
        width="800px"
        append-to-body
      >
        <el-button v-preventReClick type="primary" @click="addHandle"
        >添加管理员
        </el-button
        >
        <el-table v-loading="loading" style="margin-top: 10px" :data="gridData">
          <el-table-column
            align="center"
            property="nickName"
            label="姓名"
          ></el-table-column>
          <el-table-column
            align="center"
            property="account"
            label="账号"
          ></el-table-column>
          <el-table-column
            align="center"
            property="phoneNumber"
            label="手机号码"
          ></el-table-column>
          <el-table-column align="center" property="status" label="状态"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_normal_disable"
                :value="scope.row.status"
              />
            </template
            >
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button
              >
              <el-button
                v-preventReClick
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleSwitch(scope.row)"
              >{{ scope.row.status == 0 ? '停用' : '启用' }}
              </el-button
              >
              <el-button
                v-preventReClick
                v-if="scope.row.status == 1"
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="params.total > 0"
          :total="params.total"
          :page.sync="params.pageNum"
          :limit.sync="params.pageSize"
          @pagination="getAdmins"
        />
        <div slot="footer" class="dialog-right">
          <el-button v-preventReClick type="primary" @click="setOpen = false"
          >关 闭
          </el-button
          >
        </div>
      </el-dialog>
      <!-- 添加编辑 管理员弹框 -->
      <el-dialog
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="title"
        :visible.sync="open"
        width="500px"
        append-to-body
      >
        <el-form
          @submit.native.prevent
          ref="form"
          :model="form"
          :rules="rules"
          label-width="90px"
        >
          <el-form-item label="账号" prop="userName">
            <el-input
              v-if="title == '添加管理员'"
              oninput="value=value.replace(/[^a-zA-Z_@0-9]/g, '')"
              v-model="form.userName"
              placeholder="请输入账号"
              @blur="checkTeacherNum"
            />
            <el-input
              v-else
              oninput="value=value.replace(/[^a-zA-Z_@0-9]/g, '')"
              v-model="form.account"
              placeholder="请输入账号"
              disabled
              @blur="checkTeacherNum"
            />
          </el-form-item>
          <el-form-item label="姓名" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入名字"/>
          </el-form-item>

          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model="form.phoneNumber" placeholder="请输入手机号码"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button v-preventReClick @click="open = false">取 消</el-button>
          <el-button v-preventReClick type="primary" @click="submitForm"
          >确 定
          </el-button
          >
        </div>
      </el-dialog>
      <div slot="reference" class="shou">{{ adminNum }}</div>
    </el-popover>
  </div>
</template>

<script>
import { getAdmin_school } from '@/api/school/list'
import { getUserlnfoByUsemame } from '@/api/system/user'
import {
  addUserAdmin,
  updateUserAdmin,
  updateUserAdmin_changeStatus,
  updateUserAdmin_delete,
  getUser
} from '@/api/system/user'

export default {
  components: {},
  dicts: ['sys_normal_disable'],
  props: { schoolId: Number, adminNum: Number },
  data() {
    return {
      gridData: [],
      setOpen: false,
      loading: false,
      params: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      open: false,
      title: '添加管理员', // 表单参数
      form: {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: undefined,
        roleIds: undefined
      },
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, validator: this.$checkPhone, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '账号不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {},
  created() {
  },
  mounted() {
  },
  methods: {
    async checkTeacherNum() {
      if (this.title == '添加管理员' && this.form.userName) {
        let res
        try {
          res = await getUserlnfoByUsemame(this.form.userName, this.schoolId)
        } finally {
          if (res.data) {
            this.$modal.msg(`${res.data.nickName}已存在`)
            this.form.nickName = res.data.nickName
            this.form.phoneNumber = res.data.phoneNumber
            this.form.userId = res.data.userId
          } else {
            this.form.userId = null
          }
        }
      }
    },
    async getAdmins() {
      this.loading = true
      try {
        let params = {
          ...this.params
        }
        let res = await getAdmin_school(this.schoolId, params)
        const { code, total, rows } = res
        if (code == 200) {
          this.gridData = rows
          this.params.total = total
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    handleUpdate(row) {
      this.form = row
      this.open = true
      this.title = '编辑管理员'
    },
    addHandle() {
      this.reset()
      this.open = true
      this.title = '添加管理员'
    },
    // 删除 按钮
    handleDelete(row) {
      this.$confirm(`是否确认删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          updateUserAdmin_delete(row.userId).then(() => {
            this.$emit('refresh')
            this.$modal.msgSuccess('操作成功')
            this.open = false
            this.getAdmins()
          })
        })
        .catch(() => {
        })
    },
    // 停用 启用按钮
    handleSwitch(row) {
      this.$confirm(`是否确认${row.status == 0 ? '停用' : '启用'}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let data = JSON.parse(JSON.stringify(row))
          data.status = row.status == 0 ? 1 : 0
          getUser(data.userId).then((res) => {
            data.roleIds = res.roleIds
            updateUserAdmin_changeStatus(data).then((response) => {
              this.$modal.msgSuccess('操作成功')
              this.open = false
              this.getAdmins()
            })
          })
        })
        .catch(() => {
        })
    },
    reset() {
      this.form = {
        userId: undefined,
        nickName: undefined,
        phoneNumber: undefined,
        userName: undefined,
        roleIds: undefined
      }
      this.resetForm('form')
    },
    submitForm: function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.form.schoolId = this.schoolId
          this.form.roleIds = [6]
          if (this.title == '编辑管理员') {
            updateUserAdmin(this.form).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getAdmins()
            })
          } else {
            addUserAdmin(this.form).then(() => {
              this.$emit('refresh')
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getAdmins()
            })
          }
        }
      })
    }
  }
}
</script>
<style scoped lang="scss"></style>
